<?php

namespace App\Http\Repositories\Service;

use App\Http\Repositories\Relation\ResourceObjectRepo;
use App\Http\Repositories\Relation\TypeObjectRepo;
use App\Http\Repositories\Repository;
use App\Models\Service;
use App\Traits\HelpFunctions;
use Illuminate\Support\Facades\DB;

/**
 * 服务
 */
class ServiceRepo extends Repository
{
    use HelpFunctions;

    const MODEL = Service::class;

    public function search(array $params)
    {
        $query = $this->query()
            ->select('services.*', 'users.name as user_name', 'users.phone')
            ->leftJoin('users', 'users.id', '=', 'services.user_id');

        if (!empty($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }
        if (!empty($params['phone'])) {
            $query->where('phone', 'like', '%' . $params['phone'] . '%');
        }

        if (!empty($params['introduction'])) {
            $query->where('introduction', 'like', '%' . $params['introduction'] . '%');
        }

        if (!empty($params['sn'])) {
            $query->where('sn', 'like', '%' . $params['sn'] . '%');
        }

        if (!empty($params['user_id'])) {
            $query->where('user_id', $params['user_id']);
        }

        if (!empty($params['negotiate'])) {
            $query->where('negotiate', $params['negotiate']);
        }

        if (!empty($params['province_id'])) {
            $query->where('province_id', $params['province_id']);
        }

        if (!empty($params['city_id'])) {
            $query->where('city_id', $params['city_id']);
        }

        if (!empty($params['area_id'])) {
            $query->where('area_id', $params['area_id']);
        }

        if (!empty($params['type_ids'])) {
            $object_ids = app(TypeObjectRepo::class)->getObjectIdByTypeIds($params['type_ids']);
            $query->whereIn('id', $object_ids);
        }

        if (!empty($params['begin_price'])) {
            $query->where('price', '>=', $params['begin_price']);
        }

        if (!empty($params['end_price'])) {
            $query->where('price', '<=', $params['end_price']);
        }

        if (!empty($params['status'])) {
            $query->where('status', $params['status']);
        }

        if (!empty($params['begin_time'])) {
            $query->where('created_at', '>=', $params['begin_time']);
        }

        if (!empty($params['end_time'])) {
            $query->where('created_at', '<=', $params['end_time']);
        }

        if (!empty($params["filter_deadline"])) {
            $query->where("deadline", ">=", date("Y-m-d H:i:s"));
        }

        if (!empty($params['begin_deadline'])) {
            $query->where('deadline', '>=', $params['begin_deadline']);
        }

        if (!empty($params['end_deadline'])) {
            $query->where('deadline', '<=', $params['end_deadline']);
        }

        $query->with(['resources', 'types',"provinces","citys","areas"]);

        return $this->paginate($query, $params["paginate"] ?? true, $params["page_num"] ?? 10);
    }

    public function getOneById(int $id)
    {
        $query = $this->query()
            ->leftJoin('users', 'users.id', '=', 'services.user_id')
            ->select('services.*', 'users.name as user_name', 'users.phone')
            ->where('services.id', $id)
            ->with(['resources', 'types',"provinces","citys","areas"])
            ->first();

        return !empty($query) ? $query->toArray() : [];
    }

    public function createOne(array $params)
    {
        //service参数
        $service_args = $this->getServiceArgs($params);

        //事务处理
        DB::beginTransaction();

        try {
            //添加service数据
            $service = parent::createOne($service_args);
            $object_id = $service->id;

            //添加resource_object数据
            $resource_args = $this->getResourceObjectArgs(
                $params['resources'],
                ['type' => config('project.resource.service'), 'object_id' => $object_id]
            );
            $resource_object = new ResourceObjectRepo;
            $resource_object->createMany($resource_args);

            //添加type_object_relation数据
            $type_args = $this->getTypeObjectArgs(
                $params['types'],
                ['object_id' => $object_id, 'type' => config('project.type.service')]
            );
            $type_object = new TypeObjectRepo;
            $type_object->createMany($type_args);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            abort(500, $e->getMessage());
        }

        return $this->getOneById($object_id);
    }

    public function deleteById(int $id)
    {
        DB::beginTransaction();
        try {
            $business = $this->getOneById($id);
            parent::deleteById($id);

            $resource_object = new ResourceObjectRepo;
            $resource_object->deleteByConditions(['type' => config('project.resource.service'), 'object_id' => $id]);

            $type_object = new TypeObjectRepo;
            $type_object->deleteByConditions(['type' => config('project.type.service'), 'object_id' => $id]);

            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            abort(500, $e->getMessage());
        }
    }

    public function editById(int $id, array $params)
    {
        //handle params

        //business参数
        $service_args = $this->getServiceArgs($params);
        //delete resource_object condition
        $delete_resources = ['type' => config('project.resource.service'), 'object_id' => $id];
        $delete_type_object = ['object_id' => $id, 'type' => config('project.type.service')];

        //update args
        if (!empty($params['resources'])) {
            $resource_args = $this->getResourceObjectArgs(
                $params['resources'],
                ['type' => config('project.resource.service'), 'object_id' => $id]
            );
        }
        if (!empty($params['types'])) {
            $type_args = $this->getTypeObjectArgs(
                $params['types'],
                ['object_id' => $id, 'type' => config('project.type.service')]
            );
        }

        //begin transactin
        DB::beginTransaction();
        try {
            //更新business
            parent::editById($id, $service_args);

            //更新resource_object数据
            if (!empty($resource_args)) {
                app(ResourceObjectRepo::class)->deleteByConditions($delete_resources);
                app(ResourceObjectRepo::class)->createMany($resource_args);
            }

            //更新type_object_relation数据
            if (!empty($type_args)) {
                app(TypeObjectRepo::class)->deleteByConditions($delete_type_object);
                app(TypeObjectRepo::class)->createMany($type_args);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            abort(500, $e->getMessage());
        }
        return $this->getOneById($id);
    }
}
